/**
  * @description: 一个tab组件
  * @author: yingying.fan
  * @date: 2019/2/28 16:16
  */
import React, { Component } from 'react'
import { StyleSheet, View, TouchableOpacity, Text } from 'react-native'
import { px2dp } from 'rn-xiaobu-utils'

type Props = {
  titles: Array<any>,
  index: number,
  select: Function,
  titleStyle?: Object,
  titleSelectedStyle?: Object,
  lineSelectedStyle?: Object
}

export default class SegmentedTab extends Component<Props> {
  static defaultProps = {
    titleStyle: {
      color: '#333'
    },
    titleSelectedStyle: {},
    lineSelectedStyle: {
      position: 'absolute',
      bottom: 0,
      width: '50%',
      height: px2dp(6),
      backgroundColor: '#333'
    }
  }

  constructor (props) {
    super(props)
    this.state = {}
  }

  _renderTitleItem = (title, index) => {
    let lineStyle = []
    let textStyle = [this.props.titleStyle]
    if (this.props.index === index) {
      lineStyle.push(this.props.lineSelectedStyle)
      textStyle.push(this.props.titleSelectedStyle)
    }
    return (
      <TouchableOpacity
        activeOpacity={0.8}
        key={index}
        style={styles.tabItem}
        onPress={() => this.props.select(index)}>
        <Text style={textStyle}>{title}</Text>
        <View style={lineStyle}></View>
      </TouchableOpacity>
    )
  }

  render () {
    // let titlesLen = this.props.titles
    // let items = []
    // for (let i = 0; i < titlesLen; i++) {
    //   items.push(this._renderTitleItem(this.props.titles[i], i))
    // }
    return (
      <View style={styles.container}>
        {
          this.props.titles.map((title, index) => {
            return this._renderTitleItem(title, index)
          })
        }
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    width: '100%',
    height: px2dp(100),
    flexDirection: 'row',
    backgroundColor: '#ffffff'
  },
  tabItem: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    position: 'relative'
  }
})